﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CRM.Infrastructure.Tools
{
    public static class Config
    {
        public static string GetKey(string key)
        {
           return ConfigurationManager.AppSettings[key] ?? "";
        }

        /// <summary>
        /// 获取客户端IP地址（无视代理）
        /// </summary>
        /// <returns>若失败则返回回送地址</returns>
        public static string GetIp()
        {
            //127.0.0.1   ::::1   localhost
            // return "127.0.0.1";//正式环境请注释
            IHttpContextAccessor _httpContextAccessor = new HttpContextAccessor();
            return _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();//测试环境请注释
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        static Random Random = new Random();

        public static int Next(int min,int max)
        {
            return Random.Next(min,max);
        }
        /// <summary>
        /// 无序
        /// </summary>
        /// <returns></returns>
        public static string GUID_1() 
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }
        /// <summary>
        /// 有序
        /// </summary>
        /// <returns></returns>
        public static string GUID_2()
        {

            byte[] bytes = Guid.NewGuid().ToByteArray();
            DateTime now = DateTime.UtcNow;

            bytes[3] = (byte)(now.Year - 2021); // 假设2021年为起点
            bytes[2] = (byte)now.Month;
            bytes[1] = (byte)now.Day;
            bytes[0] = (byte)now.Hour;
            Array.Copy(BitConverter.GetBytes(now.Millisecond), 0, bytes, 4, 2);
            Array.Copy(BitConverter.GetBytes(now.Second), 0, bytes, 6, 2);
            Array.Copy(Guid.NewGuid().ToByteArray(), 0, bytes, 8, 8);

            return new Guid(bytes).ToString().Replace("-", "");

        }
    }
}
